package com.example.layered_arch.example.service;

import com.example.layered_arch.example.dto.LoginRequest;
import com.example.layered_arch.example.util.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.EmptyResultDataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class UserAuthService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Autowired
    private PasswordEncoder passwordEncoder;

    // 登录方法
    public Map<String, String> login(LoginRequest loginRequest) {
        Map<String, String> response = new HashMap<>();
        String username = loginRequest.getUsername();
        String password = loginRequest.getPassword();

        try {
            // 使用 JdbcTemplate 查询用户信息
            String sql = "SELECT password FROM users WHERE username = ?";
            String storedPassword = jdbcTemplate.queryForObject(sql, new Object[]{username}, String.class);

            if (storedPassword == null) {
                response.put("message", "用户名不存在");
            } else {
                // 如果存储的是明文密码，则直接比较
                if (storedPassword.equals(password)) {
                    String token = JwtUtil.generateToken(username); // 生成 JWT token
                    response.put("message", "登录成功");
                    response.put("token", token);
                } else {
                    response.put("message", "密码错误");
                }
            }
        } catch (EmptyResultDataAccessException e) {
            response.put("message", "用户名不存在");
        } catch (Exception e) {
            e.printStackTrace();  // 打印详细的异常堆栈
            response.put("message", "登录失败，发生了意外错误");
        }

        return response;
    }
}
